package com.david.controller;

import cn.dev33.satoken.stp.StpUtil;
import com.david.entity.AdminUser;
import com.david.entity.RegisterHr;
import com.david.service.Impl.UserLoginServiceImpl;
import com.david.vo.CardBean;
import com.david.vo.UserImage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * @author David
 */
@Controller
@Slf4j
@RequestMapping("/Admin")
public class UserLogin {

    @Resource
    private UserLoginServiceImpl userLoginService;

    @Resource
    HttpServletRequest request;

    @Resource
    StringRedisTemplate stringRedisTemplate;


    /**
     * 登录界面验证
     * @param adminUser 包含用户名和密码
     */
    @PostMapping("/login")
    @ResponseBody
    public CardBean adminLogin(@RequestBody @Validated AdminUser adminUser)
    {
        return userLoginService.adminLogin(adminUser);
    }

    /**
     * 用户注册
     * @param registerHr 用户信息
     * @return 返回状态
     */
    @PostMapping("/saveHr")
    @ResponseBody
    public CardBean saveHr(@RequestBody @Validated RegisterHr registerHr){
        return userLoginService.saveHr(registerHr);
    }

    @GetMapping("/logout")
    public String logout(){
        // redis中remove此请求的session
        log.info("执行登出session操作，登出前在线人数为：" + (stringRedisTemplate.opsForSet().size("onlineSet") - 1));
        stringRedisTemplate.opsForSet().remove("onlineSet", request.getRequestedSessionId());
        log.info("执行登出session操作，登出后在线人数为：" + (stringRedisTemplate.opsForSet().size("onlineSet") - 1));

        // 客户端中注销其session
        if((request.getSession(false) != null)) {
            log.info("用户{}已注销:", request.getSession(false).getAttribute("username").toString());
            request.getSession().invalidate();
        }

        // sa-token当前帐号下线处理
        StpUtil.logout();

        return "login.html";
    }

    @GetMapping("/loginInit")
    @ResponseBody
    public CardBean loginInit(){
        return userLoginService.loginInit();
    }

}
